/**
 * HTTP请求工具
 */
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import NProgress from 'nprogress'
import { useUserStore } from '@/stores/user'
import router from '@/router'
import type { ApiResponse } from '@/types'

// 请求重试队列
let isRefreshing = false
let failedQueue: Array<{
  resolve: (value: any) => void
  reject: (reason: any) => void
}> = []

// 处理队列中的请求
const processQueue = (error: any, token: string | null = null) => {
  failedQueue.forEach(({ resolve, reject }) => {
    if (error) {
      reject(error)
    } else {
      resolve(token)
    }
  })

  failedQueue = []
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 30000
  // 不设置默认Content-Type，让axios根据数据类型自动设置
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    NProgress.start()

    // 添加认证token
    const userStore = useUserStore()
    const token = userStore.token
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }

    // 如果不是FormData，设置默认Content-Type
    if (!(config.data instanceof FormData)) {
      config.headers = config.headers || {}
      config.headers['Content-Type'] = 'application/json'
    }
    // 如果是FormData，删除Content-Type让浏览器自动设置
    else if (config.headers && config.headers['Content-Type']) {
      delete config.headers['Content-Type']
    }

    return config
  },
  (error) => {
    NProgress.done()
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    NProgress.done()

    const { data } = response

    // 如果是文件下载等特殊响应，直接返回
    if (response.config.responseType === 'blob') {
      return response
    }

    // 正常响应
    if (response.status === 200 || response.status === 201) {
      // 直接返回响应对象，让组件自己处理data
      return response
    }

    // 其他状态码
    ElMessage.error(data.message || '请求失败')
    return Promise.reject(new Error(data.message || '请求失败'))
  },
  async (error) => {
    NProgress.done()

    const { response, config } = error
    const userStore = useUserStore()

    if (response) {
      const { status, data } = response

      switch (status) {
        case 401:
          // 如果是刷新token的请求失败，直接跳转登录
          if (config.url?.includes('/auth/token/refresh/')) {
            ElMessage.error('登录已过期，请重新登录')
            userStore.logout()
            router.push('/login')
            break
          }

          // 如果有refresh token，尝试刷新
          if (userStore.refreshToken && !isRefreshing) {
            isRefreshing = true

            try {
              const newToken = await userStore.refreshAccessToken()
              processQueue(null, newToken)

              // 重新发送原请求
              config.headers.Authorization = `Bearer ${newToken}`
              return service(config)
            } catch (refreshError) {
              processQueue(refreshError, null)
              ElMessage.error('登录已过期，请重新登录')
              userStore.logout()
              router.push('/login')
            } finally {
              isRefreshing = false
            }
          } else if (isRefreshing) {
            // 如果正在刷新token，将请求加入队列
            return new Promise((resolve, reject) => {
              failedQueue.push({ resolve, reject })
            }).then(token => {
              config.headers.Authorization = `Bearer ${token}`
              return service(config)
            }).catch(err => {
              return Promise.reject(err)
            })
          } else {
            // 没有refresh token，直接跳转登录
            ElMessage.error('登录已过期，请重新登录')
            userStore.logout()
            router.push('/login')
          }
          break
          
        case 403:
          ElMessage.error('没有权限访问该资源')
          break
          
        case 404:
          ElMessage.error('请求的资源不存在')
          break
          
        case 422:
          // 表单验证错误
          if (data.errors) {
            const errorMessages = Object.values(data.errors).flat()
            ElMessage.error(errorMessages.join(', '))
          } else {
            ElMessage.error(data.message || '请求参数错误')
          }
          break
          
        case 500:
          ElMessage.error('服务器内部错误')
          break
          
        default:
          ElMessage.error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.code === 'ECONNABORTED') {
      ElMessage.error('请求超时，请稍后重试')
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
    
    return Promise.reject(error)
  }
)

// 封装常用请求方法
export const request = {
  get<T = any>(url: string, params?: any): Promise<T> {
    // 如果有参数，手动构建查询字符串
    if (params && Object.keys(params).length > 0) {
      const searchParams = new URLSearchParams()
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
          searchParams.append(key, String(params[key]))
        }
      })
      const queryString = searchParams.toString()
      if (queryString) {
        url = url + (url.includes('?') ? '&' : '?') + queryString
      }
    }
    return service.get(url)
  },
  
  post<T = any>(url: string, data?: any, config?: any): Promise<T> {
    return service.post(url, data, config)
  },

  put<T = any>(url: string, data?: any, config?: any): Promise<T> {
    return service.put(url, data, config)
  },
  
  patch<T = any>(url: string, data?: any): Promise<T> {
    return service.patch(url, data)
  },
  
  delete<T = any>(url: string): Promise<T> {
    return service.delete(url)
  },
  
  upload<T = any>(url: string, formData: FormData): Promise<T> {
    return service.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },

  uploadPut<T = any>(url: string, formData: FormData): Promise<T> {
    return service.put(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  download(url: string, params?: any): Promise<AxiosResponse> {
    return service.get(url, {
      params,
      responseType: 'blob'
    })
  }
}

export default service
